package com.ryder.petmatediarybackend.module.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ryder.petmatediarybackend.common.exception.BusinessException;
import com.ryder.petmatediarybackend.module.admin.dto.AuditDTO;
import com.ryder.petmatediarybackend.module.admin.service.AuditManagementService;
import com.ryder.petmatediarybackend.module.admin.vo.AuditItemVO;
import com.ryder.petmatediarybackend.module.pet.entity.SysUser;
import com.ryder.petmatediarybackend.module.pet.service.SysUserService;
import com.ryder.petmatediarybackend.module.shop.entity.ShopInfo;
import com.ryder.petmatediarybackend.module.shop.entity.ShopPetCollection;
import com.ryder.petmatediarybackend.module.shop.entity.ShopProductCollection;
import com.ryder.petmatediarybackend.module.shop.entity.ShopQualification;
import com.ryder.petmatediarybackend.module.shop.service.ShopInfoService;
import com.ryder.petmatediarybackend.module.shop.service.ShopPetCollectionService;
import com.ryder.petmatediarybackend.module.shop.service.ShopProductCollectionService;
import com.ryder.petmatediarybackend.module.shop.service.ShopQualificationService;
import com.ryder.petmatediarybackend.module.social.entity.SocialPost;
import com.ryder.petmatediarybackend.module.social.service.SocialPostService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述: 审核管理服务实现类
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0
 * 更新日期: 2025-10-31
 */
@Slf4j
@Service("auditManagementService")
@RequiredArgsConstructor
public class AuditManagementServiceImpl implements AuditManagementService {

    private final ShopQualificationService shopQualificationService;
    private final ShopInfoService shopInfoService;
    private final ShopPetCollectionService shopPetCollectionService;
    private final ShopProductCollectionService shopProductCollectionService;
    private final SocialPostService socialPostService;
    private final SysUserService sysUserService;

    @Override
    public List<AuditItemVO> getPendingQualifications() {
        log.info("[获取待审核资质列表]");

        LambdaQueryWrapper<ShopQualification> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(ShopQualification::getAuditorId)
                .orderByAsc(ShopQualification::getCreateTime);

        List<ShopQualification> list = shopQualificationService.list(wrapper);
        return list.stream().map(this::convertQualificationToVO).collect(Collectors.toList());
    }

    @Override
    public List<AuditItemVO> getPendingShops() {
        log.info("[获取待审核店铺列表]");

        LambdaQueryWrapper<ShopInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(ShopInfo::getAuditorId)
                .orderByAsc(ShopInfo::getCreateTime);

        List<ShopInfo> list = shopInfoService.list(wrapper);
        return list.stream().map(this::convertShopToVO).collect(Collectors.toList());
    }

    @Override
    public List<AuditItemVO> getPendingPetCollections() {
        log.info("[获取待审核宠物合集列表]");

        LambdaQueryWrapper<ShopPetCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopPetCollection::getAuditStatus, 0)
                .orderByAsc(ShopPetCollection::getCreateTime);

        List<ShopPetCollection> list = shopPetCollectionService.list(wrapper);
        return list.stream().map(this::convertPetCollectionToVO).collect(Collectors.toList());
    }

    @Override
    public List<AuditItemVO> getPendingProductCollections() {
        log.info("[获取待审核商品合集列表]");

        LambdaQueryWrapper<ShopProductCollection> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShopProductCollection::getAuditStatus, 0)
                .orderByAsc(ShopProductCollection::getCreateTime);

        List<ShopProductCollection> list = shopProductCollectionService.list(wrapper);
        return list.stream().map(this::convertProductCollectionToVO).collect(Collectors.toList());
    }

    @Override
    public List<AuditItemVO> getPendingSocialPosts() {
        log.info("[获取待审核说说列表]");

        LambdaQueryWrapper<SocialPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.isNull(SocialPost::getAuditorId)
                .orderByAsc(SocialPost::getCreateTime);

        List<SocialPost> list = socialPostService.list(wrapper);
        return list.stream().map(this::convertSocialPostToVO).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditQualification(Long auditorId, AuditDTO dto) {
        log.info("[审核店铺资质] auditorId={}, targetId={}, auditStatus={}", 
                auditorId, dto.getTargetId(), dto.getAuditStatus());

        ShopQualification qualification = shopQualificationService.getById(dto.getTargetId());
        if (qualification == null) {
            throw new BusinessException("资质不存在");
        }

        if (qualification.getAuditorId() != null) {
            throw new BusinessException("该资质已审核，无法重复审核");
        }

        // 更新审核信息
        qualification.setAuditStatus(dto.getAuditStatus());
        qualification.setAuditRemark(dto.getAuditRemark());
        qualification.setAuditorId(auditorId);
        qualification.setAuditTime(LocalDateTime.now());

        boolean updated = shopQualificationService.updateById(qualification);
        if (!updated) {
            throw new BusinessException("审核失败");
        }

        log.info("[审核店铺资质成功] qualificationId={}, result={}", 
                dto.getTargetId(), dto.getAuditStatus() == 1 ? "通过" : "驳回");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditShop(Long auditorId, AuditDTO dto) {
        log.info("[审核店铺申请] auditorId={}, targetId={}, auditStatus={}", 
                auditorId, dto.getTargetId(), dto.getAuditStatus());

        ShopInfo shop = shopInfoService.getById(dto.getTargetId());
        if (shop == null) {
            throw new BusinessException("店铺不存在");
        }

        if (shop.getAuditorId() != null) {
            throw new BusinessException("该店铺已审核，无法重复审核");
        }

        // 更新审核信息
        shop.setAuditStatus(dto.getAuditStatus());
        shop.setAuditRemark(dto.getAuditRemark());
        shop.setAuditorId(auditorId);
        shop.setAuditTime(LocalDateTime.now());

        // 审核通过后更新状态为营业中
        if (dto.getAuditStatus() == 1) {
            shop.setStatus(1);
        }

        boolean updated = shopInfoService.updateById(shop);
        if (!updated) {
            throw new BusinessException("审核失败");
        }

        log.info("[审核店铺申请成功] shopId={}, result={}", 
                dto.getTargetId(), dto.getAuditStatus() == 1 ? "通过" : "驳回");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditPetCollection(Long auditorId, AuditDTO dto) {
        log.info("[审核宠物合集] auditorId={}, targetId={}, auditStatus={}", 
                auditorId, dto.getTargetId(), dto.getAuditStatus());

        ShopPetCollection petCollection = shopPetCollectionService.getById(dto.getTargetId());
        if (petCollection == null) {
            throw new BusinessException("宠物合集不存在");
        }

        if (petCollection.getAuditStatus() != 0) {
            throw new BusinessException("该宠物合集已审核，无法重复审核");
        }

        // 更新审核信息
        petCollection.setAuditStatus(dto.getAuditStatus());
        petCollection.setAuditRemark(dto.getAuditRemark());

        boolean updated = shopPetCollectionService.updateById(petCollection);
        if (!updated) {
            throw new BusinessException("审核失败");
        }

        log.info("[审核宠物合集成功] petCollectionId={}, result={}", 
                dto.getTargetId(), dto.getAuditStatus() == 1 ? "通过" : "驳回");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditProductCollection(Long auditorId, AuditDTO dto) {
        log.info("[审核商品合集] auditorId={}, targetId={}, auditStatus={}", 
                auditorId, dto.getTargetId(), dto.getAuditStatus());

        ShopProductCollection productCollection = shopProductCollectionService.getById(dto.getTargetId());
        if (productCollection == null) {
            throw new BusinessException("商品合集不存在");
        }

        if (productCollection.getAuditStatus() != 0) {
            throw new BusinessException("该商品合集已审核，无法重复审核");
        }

        // 更新审核信息
        productCollection.setAuditStatus(dto.getAuditStatus());
        productCollection.setAuditRemark(dto.getAuditRemark());

        boolean updated = shopProductCollectionService.updateById(productCollection);
        if (!updated) {
            throw new BusinessException("审核失败");
        }

        log.info("[审核商品合集成功] productCollectionId={}, result={}", 
                dto.getTargetId(), dto.getAuditStatus() == 1 ? "通过" : "驳回");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditSocialPost(Long auditorId, AuditDTO dto) {
        log.info("[审核说说] auditorId={}, targetId={}, auditStatus={}", 
                auditorId, dto.getTargetId(), dto.getAuditStatus());

        SocialPost socialPost = socialPostService.getById(dto.getTargetId());
        if (socialPost == null) {
            throw new BusinessException("说说不存在");
        }

        if (socialPost.getAuditorId() != null) {
            throw new BusinessException("该说说已审核，无法重复审核");
        }

        // 更新审核信息
        socialPost.setAuditStatus(dto.getAuditStatus());
        socialPost.setAuditRemark(dto.getAuditRemark());
        socialPost.setAuditorId(auditorId);
        socialPost.setAuditTime(LocalDateTime.now());

        // 审核通过后更新状态为正常，驳回后更新状态为违规
        if (dto.getAuditStatus() == 1) {
            socialPost.setStatus(1); // 正常
        } else if (dto.getAuditStatus() == 2) {
            socialPost.setStatus(3); // 违规
        }

        boolean updated = socialPostService.updateById(socialPost);
        if (!updated) {
            throw new BusinessException("审核失败");
        }

        log.info("[审核说说成功] socialPostId={}, result={}", 
                dto.getTargetId(), dto.getAuditStatus() == 1 ? "通过" : "驳回");
    }

    @Override
    public List<AuditItemVO> getAllPendingAudits() {
        log.info("[获取所有待审核项目]");

        List<AuditItemVO> allAudits = new ArrayList<>();
        
        // 添加所有待审核项目
        allAudits.addAll(getPendingQualifications());
        allAudits.addAll(getPendingShops());
        allAudits.addAll(getPendingPetCollections());
        allAudits.addAll(getPendingProductCollections());
        allAudits.addAll(getPendingSocialPosts());

        // 按创建时间排序
        allAudits.sort(Comparator.comparing(AuditItemVO::getCreateTime));

        return allAudits;
    }

    // ==================== 私有转换方法 ====================

    private AuditItemVO convertQualificationToVO(ShopQualification qualification) {
        AuditItemVO vo = new AuditItemVO();
        vo.setId(qualification.getId());
        vo.setAuditType(1);
        vo.setAuditTypeText("店铺资质");
        
        // 获取店铺信息
        ShopInfo shop = shopInfoService.getById(qualification.getShopId());
        if (shop != null) {
            vo.setShopId(shop.getId());
            vo.setShopName(shop.getShopName());
            vo.setApplicantId(shop.getUserId());
            
            // 获取申请人信息
            SysUser user = sysUserService.getById(shop.getUserId());
            if (user != null) {
                vo.setApplicantName(user.getUsername());
            }
        }

        vo.setTitle(qualification.getQualificationName());
        vo.setDescription("编号：" + (qualification.getQualificationNumber() != null ? qualification.getQualificationNumber() : "无"));
        vo.setQualificationType(qualification.getQualificationType());
        vo.setQualificationTypeText(getQualificationTypeText(qualification.getQualificationType()));

        // 解析图片
        if (qualification.getQualificationImages() != null) {
            vo.setImages(JSONUtil.toList(qualification.getQualificationImages(), String.class));
        }

        vo.setAuditStatus(qualification.getAuditStatus());
        vo.setAuditStatusText(getAuditStatusText(qualification.getAuditStatus()));
        vo.setAuditRemark(qualification.getAuditRemark());
        vo.setAuditorId(qualification.getAuditorId());
        vo.setAuditTime(qualification.getAuditTime());
        vo.setCreateTime(qualification.getCreateTime());
        vo.setUpdateTime(qualification.getUpdateTime());

        return vo;
    }

    private AuditItemVO convertShopToVO(ShopInfo shop) {
        AuditItemVO vo = new AuditItemVO();
        vo.setId(shop.getId());
        vo.setAuditType(2);
        vo.setAuditTypeText("店铺申请");
        vo.setApplicantId(shop.getUserId());
        vo.setShopId(shop.getId());
        vo.setShopName(shop.getShopName());

        // 获取申请人信息
        SysUser user = sysUserService.getById(shop.getUserId());
        if (user != null) {
            vo.setApplicantName(user.getUsername());
        }

        vo.setTitle(shop.getShopName());
        vo.setDescription(shop.getAddress());

        // 收集门面和内部图片
        List<String> images = new ArrayList<>();
        if (shop.getCoverImage() != null) {
            images.add(shop.getCoverImage());
        }
        if (shop.getFacadeImages() != null) {
            images.addAll(JSONUtil.toList(shop.getFacadeImages(), String.class));
        }
        if (shop.getInteriorImages() != null) {
            images.addAll(JSONUtil.toList(shop.getInteriorImages(), String.class));
        }
        vo.setImages(images);

        vo.setAuditStatus(shop.getAuditStatus());
        vo.setAuditStatusText(getAuditStatusText(shop.getAuditStatus()));
        vo.setAuditRemark(shop.getAuditRemark());
        vo.setAuditorId(shop.getAuditorId());
        vo.setAuditTime(shop.getAuditTime());
        vo.setCreateTime(shop.getCreateTime());
        vo.setUpdateTime(shop.getUpdateTime());

        return vo;
    }

    private AuditItemVO convertPetCollectionToVO(ShopPetCollection petCollection) {
        AuditItemVO vo = new AuditItemVO();
        vo.setId(petCollection.getId());
        vo.setAuditType(3);
        vo.setAuditTypeText("宠物合集");

        // 获取店铺信息
        ShopInfo shop = shopInfoService.getById(petCollection.getShopId());
        if (shop != null) {
            vo.setShopId(shop.getId());
            vo.setShopName(shop.getShopName());
            vo.setApplicantId(shop.getUserId());

            // 获取申请人信息
            SysUser user = sysUserService.getById(shop.getUserId());
            if (user != null) {
                vo.setApplicantName(user.getUsername());
            }
        }

        vo.setTitle(petCollection.getPetName());
        vo.setDescription(petCollection.getDescription());

        // 解析图片
        if (petCollection.getImages() != null) {
            vo.setImages(JSONUtil.toList(petCollection.getImages(), String.class));
        }

        vo.setAuditStatus(petCollection.getAuditStatus());
        vo.setAuditStatusText(getAuditStatusText(petCollection.getAuditStatus()));
        vo.setAuditRemark(petCollection.getAuditRemark());
        vo.setCreateTime(petCollection.getCreateTime());
        vo.setUpdateTime(petCollection.getUpdateTime());

        return vo;
    }

    private AuditItemVO convertProductCollectionToVO(ShopProductCollection productCollection) {
        AuditItemVO vo = new AuditItemVO();
        vo.setId(productCollection.getId());
        vo.setAuditType(4);
        vo.setAuditTypeText("商品合集");

        // 获取店铺信息
        ShopInfo shop = shopInfoService.getById(productCollection.getShopId());
        if (shop != null) {
            vo.setShopId(shop.getId());
            vo.setShopName(shop.getShopName());
            vo.setApplicantId(shop.getUserId());

            // 获取申请人信息
            SysUser user = sysUserService.getById(shop.getUserId());
            if (user != null) {
                vo.setApplicantName(user.getUsername());
            }
        }

        vo.setTitle(productCollection.getProductName());
        vo.setDescription(productCollection.getDescription());

        // 解析图片
        if (productCollection.getImages() != null) {
            vo.setImages(JSONUtil.toList(productCollection.getImages(), String.class));
        }

        vo.setAuditStatus(productCollection.getAuditStatus());
        vo.setAuditStatusText(getAuditStatusText(productCollection.getAuditStatus()));
        vo.setAuditRemark(productCollection.getAuditRemark());
        vo.setCreateTime(productCollection.getCreateTime());
        vo.setUpdateTime(productCollection.getUpdateTime());

        return vo;
    }

    private AuditItemVO convertSocialPostToVO(SocialPost socialPost) {
        AuditItemVO vo = new AuditItemVO();
        vo.setId(socialPost.getId());
        vo.setAuditType(5);
        vo.setAuditTypeText("说说审核");
        vo.setApplicantId(socialPost.getUserId());

        // 获取发布人信息
        SysUser user = sysUserService.getById(socialPost.getUserId());
        if (user != null) {
            vo.setApplicantName(user.getUsername());
        }

        vo.setTitle(getPostTypeText(socialPost.getPostType()));
        vo.setDescription(socialPost.getContent());

        // 解析图片
        if (socialPost.getMediaUrls() != null) {
            vo.setImages(JSONUtil.toList(socialPost.getMediaUrls(), String.class));
        }

        vo.setAuditStatus(socialPost.getAuditStatus());
        vo.setAuditStatusText(getAuditStatusText(socialPost.getAuditStatus()));
        vo.setAuditRemark(socialPost.getAuditRemark());
        vo.setAuditorId(socialPost.getAuditorId());
        vo.setAuditTime(socialPost.getAuditTime());
        vo.setCreateTime(socialPost.getCreateTime());
        vo.setUpdateTime(socialPost.getUpdateTime());

        return vo;
    }

    private String getPostTypeText(Integer postType) {
        if (postType == null) return "未知";
        return switch (postType) {
            case 1 -> "宠物圈子";
            case 2 -> "社交小圈子";
            case 3 -> "店铺圈子";
            default -> "未知";
        };
    }

    private String getQualificationTypeText(Integer qualificationType) {
        if (qualificationType == null) return "未知";
        return switch (qualificationType) {
            case 1 -> "营业执照";
            case 2 -> "动物诊疗许可证";
            case 3 -> "其他";
            default -> "未知";
        };
    }

    private String getAuditStatusText(Integer auditStatus) {
        if (auditStatus == null) return "未知";
        return switch (auditStatus) {
            case 0 -> "待审核";
            case 1 -> "审核通过";
            case 2 -> "审核驳回";
            default -> "未知";
        };
    }
}

